/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2023/4/20 23:33:03
 *        Description: 暂无
 ***********************************************************************/


using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Web.Admin.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;
using static CoreCms.Net.Configuration.GlobalEnumVars;

namespace CoreCms.Net.Web.Admin.Controllers
{
    /// <summary>
    /// 支付宝支付配置
    ///</summary>
    [Description("支付宝支付配置")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]
    public class CoreCmsAlipayConfigController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IAlipayConfigServices _coreCmsAlipayConfigServices;

        /// <summary>
        /// 构造函数
        ///</summary>
        public CoreCmsAlipayConfigController(IWebHostEnvironment webHostEnvironment
            , IAlipayConfigServices coreCmsAlipayConfigServices
            )
        {
            _webHostEnvironment = webHostEnvironment;
            _coreCmsAlipayConfigServices = coreCmsAlipayConfigServices;
        }

        #region 获取列表============================================================
        // POST: Api/CoreCmsAlipayConfig/GetPageList
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsAlipayConfig>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreCmsAlipayConfig, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                "appId" => p => p.appId,
                "publicKey" => p => p.publicKey,
                "privateKey" => p => p.privateKey,
                "serverUrl" => p => p.serverUrl,
                "signType" => p => p.signType,
                "appPublicCert" => p => p.appPublicCert,
                "alipayPublicCert" => p => p.alipayPublicCert,
                "alipayRootCert" => p => p.alipayRootCert,
                "appType" => p => p.appType,
                "notifyUrl" => p => p.notifyUrl,
                "refundUrl" => p => p.refundUrl,
                "jumpUrl" => p => p.jumpUrl,
                "isEnable" => p => p.isEnable,
                "isDefault" => p => p.isDefault,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选

            //序列 int
            var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
            //支付宝开放平台AppId varchar
            var appId = Request.Form["appId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(appId))
            {
                where = where.And(p => p.appId.Contains(appId));
            }
            //支付宝公钥 varchar
            var publicKey = Request.Form["publicKey"].FirstOrDefault();
            if (!string.IsNullOrEmpty(publicKey))
            {
                where = where.And(p => p.publicKey.Contains(publicKey));
            }
            //应用私钥 varchar
            var privateKey = Request.Form["privateKey"].FirstOrDefault();
            if (!string.IsNullOrEmpty(privateKey))
            {
                where = where.And(p => p.privateKey.Contains(privateKey));
            }
            //服务网关地址 varchar
            var serverUrl = Request.Form["serverUrl"].FirstOrDefault();
            if (!string.IsNullOrEmpty(serverUrl))
            {
                where = where.And(p => p.serverUrl.Contains(serverUrl));
            }
            //签名类型 varchar
            var signType = Request.Form["signType"].FirstOrDefault();
            if (!string.IsNullOrEmpty(signType))
            {
                where = where.And(p => p.signType.Contains(signType));
            }
            //应用公钥证书 varchar
            var appPublicCert = Request.Form["appPublicCert"].FirstOrDefault();
            if (!string.IsNullOrEmpty(appPublicCert))
            {
                where = where.And(p => p.appPublicCert.Contains(appPublicCert));
            }
            //支付宝公钥证书 varchar
            var alipayPublicCert = Request.Form["alipayPublicCert"].FirstOrDefault();
            if (!string.IsNullOrEmpty(alipayPublicCert))
            {
                where = where.And(p => p.alipayPublicCert.Contains(alipayPublicCert));
            }
            //支付宝根证书 varchar
            var alipayRootCert = Request.Form["alipayRootCert"].FirstOrDefault();
            if (!string.IsNullOrEmpty(alipayRootCert))
            {
                where = where.And(p => p.alipayRootCert.Contains(alipayRootCert));
            }
            //应用类型 varchar
            var appType = Request.Form["appType"].FirstOrDefault();
            if (!string.IsNullOrEmpty(appType))
            {
                where = where.And(p => p.appType.Contains(appType));
            }
            //支付宝支付回调通知 varchar
            var notifyUrl = Request.Form["notifyUrl"].FirstOrDefault();
            if (!string.IsNullOrEmpty(notifyUrl))
            {
                where = where.And(p => p.notifyUrl.Contains(notifyUrl));
            }
            //支付宝退款回调 varchar
            var refundUrl = Request.Form["refundUrl"].FirstOrDefault();
            if (!string.IsNullOrEmpty(refundUrl))
            {
                where = where.And(p => p.refundUrl.Contains(refundUrl));
            }
            //支付跳转地址 varchar
            var jumpUrl = Request.Form["jumpUrl"].FirstOrDefault();
            if (!string.IsNullOrEmpty(jumpUrl))
            {
                where = where.And(p => p.jumpUrl.Contains(jumpUrl));
            }
            //是否启用 bit
            var isEnable = Request.Form["isEnable"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isEnable) && isEnable.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isEnable == true);
            }
            else if (!string.IsNullOrEmpty(isEnable) && isEnable.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isEnable == false);
            }
            //当前多端默认 bit
            var isDefault = Request.Form["isDefault"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isDefault == true);
            }
            else if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isDefault == false);
            }
            //获取数据
            var list = await _coreCmsAlipayConfigServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/CoreCmsAlipayConfig/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var aliPayPayTradeType = EnumHelper.EnumToList<AliPayPayTradeType>();
            jm.data = new
            {
                aliPayPayTradeType
            };

            return jm;
        }
        #endregion

        #region 创建数据============================================================
        // POST: Api/CoreCmsAlipayConfig/GetCreate
        /// <summary>
        /// 创建数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public AdminUiCallBack GetCreate()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var aliPayPayTradeType = EnumHelper.EnumToList<AliPayPayTradeType>();
            jm.data = new
            {
                aliPayPayTradeType
            };

            return jm;
        }
        #endregion

        #region 创建提交============================================================
        // POST: Api/CoreCmsAlipayConfig/DoCreate
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public async Task<AdminUiCallBack> DoCreate([FromBody] CoreCmsAlipayConfig entity)
        {
            var jm = await _coreCmsAlipayConfigServices.InsertAsync(entity);
            return jm;
        }
        #endregion

        #region 编辑数据============================================================
        // POST: Api/CoreCmsAlipayConfig/GetEdit
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据")]
        public async Task<AdminUiCallBack> GetEdit([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsAlipayConfigServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;

            var aliPayPayTradeType = EnumHelper.EnumToList<AliPayPayTradeType>();
            jm.data = new
            {
                model,
                aliPayPayTradeType
            };

            return jm;
        }
        #endregion

        #region 编辑提交============================================================
        // POST: Api/CoreCmsAlipayConfig/Edit
        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑提交")]
        public async Task<AdminUiCallBack> DoEdit([FromBody] CoreCmsAlipayConfig entity)
        {
            var jm = await _coreCmsAlipayConfigServices.UpdateAsync(entity);
            return jm;
        }
        #endregion

        #region 删除数据============================================================
        // POST: Api/CoreCmsAlipayConfig/DoDelete/10
        /// <summary>
        /// 单选删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("单选删除")]
        public async Task<AdminUiCallBack> DoDelete([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsAlipayConfigServices.ExistsAsync(p => p.id == entity.id, true);
            if (!model)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            jm = await _coreCmsAlipayConfigServices.DeleteByIdAsync(entity.id);

            return jm;
        }
        #endregion

        #region 预览数据============================================================
        // POST: Api/CoreCmsAlipayConfig/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsAlipayConfigServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = model;

            return jm;
        }
        #endregion

        #region 设置是否启用============================================================
        // POST: Api/CoreCmsAlipayConfig/DoSetisEnable/10
        /// <summary>
        /// 设置是否启用
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否启用")]
        public async Task<AdminUiCallBack> DoSetisEnable([FromBody] FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsAlipayConfigServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isEnable = (bool)entity.data;

            var bl = await _coreCmsAlipayConfigServices.UpdateAsync(p => new CoreCmsAlipayConfig() { isEnable = oldModel.isEnable }, p => p.id == oldModel.id);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

        #region 设置当前多端默认============================================================
        // POST: Api/CoreCmsAlipayConfig/DoSetisDefault/10
        /// <summary>
        /// 设置当前多端默认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置当前多端默认")]
        public async Task<AdminUiCallBack> DoSetisDefault([FromBody] FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsAlipayConfigServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isDefault = (bool)entity.data;

            var bl = await _coreCmsAlipayConfigServices.UpdateAsync(p => new CoreCmsAlipayConfig() { isDefault = oldModel.isDefault }, p => p.id == oldModel.id);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion


    }
}
